'use strict';


const axios = require('axios')
const urljoin = require('url-join')
const semver = require('semver')
const log1 = require('@renwang-0103/logo')

function getNpmInfo(npmNmae, registry) {
  // console.log(npmNmae, registry, '我看看npm的名字');

  if (npmNmae) {
    const regis = registry || getDefaultRegistry(true)
    const npmurl = urljoin(regis, npmNmae)
    console.log(npmurl, 'npmurl');
    // 拿到当前npm包的信息
    return axios.get(npmurl).then(res => {
      // console.log(res, 'res');
      if (res.status === 200) {
        return res.data
      } else {
        return null
      }
    }).catch(err => {
      return Promise.reject(err)
    })
    if (registry) {

    }
  } else {
    return null
  }
  return 'Hello from';
}

async function getNpmVersion(npmName, registry) {
  const data = await getNpmInfo(npmName, registry)
  // console.log(data, 'data');
  if (data) {
    return Object.keys(data.versions)
  } else {
    return []
  }
}

/** 获取所有满足条件的版本号,   */
function getNpmSemverVersion(baseVersion, versions) {
  // sort 排序，从大到小 semver是封装好的npm库，具体用法看npm
  versions = versions.filter(version => semver.satisfies(version, `^${baseVersion}`)).sort((a, b) => semver.gt(b, a))
  return versions
}

async function getNpmSemverVersions(baseVersion, npmName, registry) {
  const versions = await getNpmVersion(npmName, registry)
  const newVersions = getNpmSemverVersion(baseVersion, versions)
  // console.log(newVersions, '1');
  if (newVersions && newVersions.length > 0) {
    return newVersions[0]
  }
  // console.log(newVersions, 'jsdfjj');
}

async function getLatestVesion(npmName, registry) {
  const versions = await getNpmVersion(npmName, registry)
  // console.log(versions, 'versions');
  log1.verbose('versions', versions)
  if (versions) {
    return versions.sort((a, b) => {
      return semver.gt(b, a) ? 1 : -1
    })[0]
     
  }
  return null
}

function getDefaultRegistry(isOrigin = false) {
  return isOrigin ? 'https://registry.npmjs.org' : 'https://registry.npm.taobao.org'
}
module.exports = {getLatestVesion, getNpmInfo, getNpmVersion, getNpmSemverVersions, getDefaultRegistry };